﻿using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;

namespace ThresholdAssistant.ConfigSdk
{
    /// <summary>
    /// 通用的JSON配置文件信息
    /// </summary>
    internal class ComJsonConf
    {
        /// <summary>
        /// 线程对象锁
        /// </summary>
        private static readonly object lock_Obj = new object();

        /// <summary>
        /// Json配置缓存信息
        /// </summary>
        private static readonly Dictionary<string, IConfiguration> JsonConfigCache = new Dictionary<string, IConfiguration>();

        /// <summary>
        /// 根据文件目录+文件名称获取Json配置
        /// </summary>
        /// <param name="fileDir">文件目录(格式：D:\JsonConfigs)</param>
        /// <param name="fileName">文件名称（格式：xxx.json）</param>
        /// <returns></returns>
        public static IConfiguration GetJsonConfiguration(string fileDir = null, string fileName = "appsettings.json")
        {
            if (string.IsNullOrEmpty(fileDir))
            {
                //默认读取根目录配置
                fileDir = AppContext.BaseDirectory;
            }

            var filePath = Path.Combine(fileDir, fileName);
            if (!JsonConfigCache.ContainsKey(filePath))
            {
                lock (lock_Obj)
                {
                    if (!JsonConfigCache.ContainsKey(filePath))
                    {
                        ConfigurationBuilder builder = new ConfigurationBuilder();
                        IConfigurationBuilder configBuilder = FileConfigurationExtensions.SetBasePath(builder, fileDir);//设置配置文件基础目录
                        IConfigurationRoot configuration = JsonConfigurationExtensions.AddJsonFile(configBuilder, fileName, true, true).Build();//返回编译结果
                        JsonConfigCache.Add(filePath, configuration);
                    }
                }
            }
            return JsonConfigCache[filePath];
        }
    }
}